package com.ljye.jg.ljye.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.ljye.jg.ljye.App;
import com.ljye.jg.ljye.R;
import com.ljye.jg.ljye.bean.Login_Date;
import com.ljye.jg.ljye.utils.HttpCallBackListener;
import com.ljye.jg.ljye.utils.HttpUtils;
import com.ljye.jg.ljye.utils.Http_wx;
import com.ljye.jg.ljye.utils.PrefParams;
import com.ljye.jg.ljye.utils.Utils;
import com.tencent.connect.UserInfo;
import com.tencent.connect.common.Constants;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Activity_Land extends Activity {
    private static final String TAG = "Activity_Land_A";
    private Intent intent;
    private EditText phone;//手机号
    private EditText pass_word;//密码
    private Button login;//登录
    private TextView register;//注册
    private TextView retrieve;//找回
    private ImageView weixin;//微信
    private ImageView qq;//qq
    private ImageView weibo;//微博
    private OkHttpClient client;
    private Tencent mTencent;
    private IUiListener loginListener;
    //    ----------------------------------------------------
    private IWXAPI api;
    public View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.login://登录
                    initLogin();
                    break;
                case R.id.register://注册
                    intent = new Intent(Activity_Land.this, Activity_Register.class);
                    startActivity(intent);
                    break;
                case R.id.retrieve://找回密码
                    intent = new Intent(Activity_Land.this, Activity_Retrieve.class);
                    startActivity(intent);
                    break;
                case R.id.weixin:
                    weixin();
                    break;
                case R.id.qq:
                    qqLogin(view);
                    break;
                case R.id.weibo:
                    break;

                default:
                    break;
            }
        }
    };
    private ReceiveBroadCast receiveBroadCast;

    private void weixin() {
        if (api == null) {
            api = WXAPIFactory.createWXAPI(Activity_Land.this, App.WX_APPID, true);
        }
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wx_login_duzun";
        api.sendReq(req);
    }

    @Override
    public void onResume() {
        super.onResume();
        receiveBroadCast = new ReceiveBroadCast();
        IntentFilter filter = new IntentFilter();
        filter.addAction("authlogin");
        Activity_Land.this.registerReceiver(receiveBroadCast, filter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Activity_Land.this.unregisterReceiver(receiveBroadCast);
    }

    public void getAccessToken() {
        SharedPreferences WxSp = Activity_Land.this.getApplicationContext()
                .getSharedPreferences(PrefParams.spName, Context.MODE_PRIVATE);
        String code = WxSp.getString(PrefParams.CODE, "");
        final SharedPreferences.Editor WxSpEditor = WxSp.edit();
        Log.d(TAG, "-----获取到的code----" + code);
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
                + App.WX_APPID
                + "&secret="
                + App.WX_APPSecret
                + "&code="
                + code
                + "&grant_type=authorization_code";
        Log.d(TAG, "--------即将获取到的access_token的地址--------");
        Http_wx.sendHttpRequest(url, new HttpCallBackListener() {
            @Override
            public void onFinish(String response) {

                //解析以及存储获取到的信息
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    Log.d(TAG, "-----获取到的json数据1-----" + jsonObject.toString());
                    String access_token = jsonObject.getString("access_token");
                    Log.d(TAG, "--------获取到的access_token的地址--------" + access_token);
                    String openid = jsonObject.getString("openid");
                    String refresh_token = jsonObject.getString("refresh_token");
                    if (!access_token.equals("")) {
                        WxSpEditor.putString(PrefParams.ACCESS_TOKEN, access_token);
                        WxSpEditor.apply();
                    }
                    if (!refresh_token.equals("")) {
                        WxSpEditor.putString(PrefParams.REFRESH_TOKEN, refresh_token);
                        WxSpEditor.apply();
                    }
                    if (!openid.equals("")) {
                        WxSpEditor.putString(PrefParams.WXOPENID, openid);
                        WxSpEditor.apply();
                        getPersonMessage(access_token, openid);

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Exception e) {
                Toast.makeText(Activity_Land.this, "通过code获取数据没有成功", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void getPersonMessage(String access_token, String openid) {
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token="
                + access_token
                + "&openid="
                + openid;
        Http_wx.sendHttpRequest(url, new HttpCallBackListener() {
            @Override
            public void onFinish(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    Log.d(TAG, "------获取到的个人信息------" + jsonObject.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Exception e) {
                Toast.makeText(Activity_Land.this, "通过openid获取数据没有成功", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void initLogin() {
        final String mobile = phone.getText().toString().trim();
        final String password = pass_word.getText().toString().trim();
        if (TextUtils.isEmpty(mobile) || TextUtils.isEmpty(password)) {
            Utils.showToast(Activity_Land.this, "用户名和密码不能为空哦！");
            return;
        }

        new Thread() {
            @Override
            public void run() {
                RequestBody body = new FormBody.Builder()
//                        .add("mobile", mobile)//添加键值对
//                        .add("password", password)
                        .add("mobile", "15601948562")//添加键值对
                        .add("password", "123456")
                        .build();
                Request request = new Request.Builder()
                        .url(HttpUtils.PATH + "/login")
                        .addHeader("Accept", HttpUtils.MYAPP)
                        .post(body)
                        .build();
                try {
                    Response execute = client.newCall(request).execute();
                    String string = execute.body().string();
                    Log.d("登录返回信息", string);
//                    int status_code = login_date.getStatus_code();
//                    if (status_code == 200) {
                    if (execute.isSuccessful()) {
                        Gson gson = new Gson();
                        Login_Date login_date = gson.fromJson(string, Login_Date.class);
                        //设置全局token
                        String token = login_date.getData().getToken().getToken();
                        App application = (App) getApplication();
                        application.setToken(token);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                login.setClickable(false);
                                Utils.showToast(Activity_Land.this, "登录成功！");
                            }
                        });

                        Intent intent = new Intent(Activity_Land.this, MainActivity.class);
                        startActivity(intent);
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                login.setClickable(true);
                                Utils.showToast(Activity_Land.this, "用户名或密码错误哦！");
                            }
                        });

                    }

                } catch (IOException e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Utils.showToast(Activity_Land.this, "连接超时，请检查网络及重试");
                        }
                    });
                }
            }
        }.start();


    }
//   ---------------------------------------------------

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity__land);
        initView();
        client = new OkHttpClient.Builder()
                .connectTimeout(5, TimeUnit.SECONDS)//超时时间
                .build();
        login.setOnClickListener(listener);
        register.setOnClickListener(listener);
        retrieve.setOnClickListener(listener);
        weixin.setOnClickListener(listener);
        qq.setOnClickListener(listener);
        weibo.setOnClickListener(listener);


    }

    private void initView() {
        phone = (EditText) findViewById(R.id.phone);
        pass_word = (EditText) findViewById(R.id.password);
        login = (Button) findViewById(R.id.login);
        register = (TextView) findViewById(R.id.register);
        retrieve = (TextView) findViewById(R.id.retrieve);
        weixin = (ImageView) findViewById(R.id.weixin);
        qq = (ImageView) findViewById(R.id.qq);
        weibo = (ImageView) findViewById(R.id.weibo);
    }

    //收起软键盘
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (getCurrentFocus() != null && getCurrentFocus().getWindowToken() != null) {
                manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
        return super.onTouchEvent(event);
    }

    /**
     * 实现QQ第三方登录
     */

    public void qqLogin(View view) {
        mTencent = Tencent.createInstance("1105875360", this);
        mTencent.login(this, "all", loginListener);
        loginListener = new IUiListener() {
            @Override
            public void onComplete(Object o) {
                //登录成功后回调该方法,可以跳转相关的页面
                Toast.makeText(Activity_Land.this, "登录成功", Toast.LENGTH_SHORT).show();
                JSONObject object = (JSONObject) o;
                try {
                    String accessToken = object.getString("access_token");
                    String expires = object.getString("expires_in");
                    String openID = object.getString("openid");
                    mTencent.setAccessToken(accessToken, expires);
                    mTencent.setOpenId(openID);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(UiError uiError) {
                //出错
            }

            @Override
            public void onCancel() {
                //取消
            }
        };
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constants.REQUEST_LOGIN) {
            if (resultCode == -1) {
                Tencent.onActivityResultData(requestCode, resultCode, data, loginListener);
                Tencent.handleResultData(data, loginListener);
                UserInfo info = new UserInfo(this, mTencent.getQQToken());
                info.getUserInfo(new IUiListener() {
                    @Override
                    public void onComplete(Object o) {
                        try {
//                            "is_yellow_year_vip": "0",
//                                    "ret": 0,
//                                    "figureurl_qq_1":
//                            "http://q.qlogo.cn/qqapp/222222/8C75BBE3DC6B0E9A64BD31449A3C8CB0/40",
//                                    "figureurl_qq_2":
//                            "http://q.qlogo.cn/qqapp/222222/8C75BBE3DC6B0E9A64BD31449A3C8CB0/100",
//                                    "nickname": "小罗",
//                                    "yellow_vip_level": "0",
//                                    "msg": "",
//                                    "figureurl_1":
//                            "http://qzapp.qlogo.cn/qzapp/222222/8C75BBE3DC6B0E9A64BD31449A3C8CB0/50",
//                                    "vip": "0",
//                                    "level": "0",
//                                    "figureurl_2":
//                            "http://qzapp.qlogo.cn/qzapp/222222/8C75BBE3DC6B0E9A64BD31449A3C8CB0/100",
//                                    "is_yellow_vip": "0",
//                                    "gender": "男",
//                                    "figureurl":
//                            "http://qzapp.qlogo.cn/qzapp/222222/8C75BBE3DC6B0E9A64BD31449A3C8CB0/30"

                            JSONObject info = (JSONObject) o;
                            String nickName = info.getString("nickname");//获取用户昵称
                            String iconUrl = info.getString("figureurl_qq_2");//获取用户头像的url
                            Toast.makeText(Activity_Land.this, "昵称：" + nickName, Toast.LENGTH_SHORT).show();
//                            Glide.with(MainActivity.this).load(iconUrl).into(icon);//Glide解析获取用户头像
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(UiError uiError) {//错误
                    }

                    @Override
                    public void onCancel() {//取消
                    }
                });
            }
        }
    }

    class ReceiveBroadCast extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            getAccessToken();
            //登录成功 进主页面
//            Intent intent1 = new Intent(Activity_Land.this, MainActivity.class);
//            startActivity(intent1);
        }
    }
}
